﻿using maxiaopeng.Help;
using maxiaopeng.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Security;

namespace maxiaopeng.Controllers
{
    public class LoginController : ApiController
    {

        // GET: api/Login
        public IHttpActionResult Login([FromBody] Users user)
        {
            using(CRMDBEntities db=new CRMDBEntities())
            {
                var list = db.Users.SingleOrDefault(p => p.LoginName == user.LoginName);
                List<int> rid = new List<int>();
                List<string> rolelist = new List<string>();
                var roleid = db.UserRoles.Where(x => x.UserId == list.Id).Select(x => new {
                    rid = x.RoleId
                }).ToList();
                foreach (var item in roleid)
                {
                    rid.Add(Convert.ToInt32(item.rid));
                }
                foreach (var item in rid)
                {
                    var rolename = db.Roles.FirstOrDefault(x => x.Id == item);
                    rolelist.Add(rolename.Name);
                }
                if (list != null)
                {
                    if (list.IsLockout == (1))
                    {
                        return Json(new { code = -1, msg = "该用户已锁定" });
                    }else
                    {
                        if (user.Password == list.Password)
                        {
                            FormsAuthentication.SetAuthCookie(user.LoginName, true);
                            return Json(new { code = 0, msg = "登录成功!" ,
                                token =list.Id,
                                uid=list.Id,
                                roleNames = rolelist,
                            });
                        }
                        else
                        {
                            return Json(new { code = -1, msg = "密码错误!" });
                        }
                    }
                }
                else
                {
                    return Json(new { code = -1, msg = "用户名不存在!" });
                }
            }
        }
    }
}
